from django.http import HttpRequest
from functools import wraps
from django.conf import settings

from gis.common.exceptions import BizException
from itpay.core.agency import agency_service
from itpay.core.agency.errors import *
from gis.common.safe_dog import client as safe_dog_client
from itpay.utils.requests_utils import get_request_ip


def require_login(check_white_ip=True, check_vcode=False):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            request = args[0]
            assert isinstance(request, HttpRequest)

            token = request.META.get('HTTP_X_AUTH_TOKEN')  # token被django转换成HTTP_TOKEN存放在META里面.

            if not token:
                raise BizException(ERROR_TOKEN_PARAM_EXISTS)

            user = request.user_dict if hasattr(request, 'user_dict') else agency_service.get_agency_by_token(token)
            request.token = token

            if not user:
                raise BizException(ERROR_AGENCY_TOKEN_EXPIRE)
            ip = None
            if check_white_ip:
                check_user_white_ip(request, user, ip)

            if check_vcode:
                check_user_vcode(request, user, ip)

            request.user = user
            request.user_id = user['id']
            return func(*args, **kwargs)

        return wrapper

    return decorator


def check_user_white_ip(request, user, ip=None):
    ip = ip or get_request_ip(request)
    if user['white_ips'] and ip not in user['white_ips']:
        raise BizException(ERROR_IP_NOT_IN_WHITE, ip)


def check_user_vcode(request, user, ip=None):
    if settings.IS_PRODUCTION_ENV and user['use_vcode']:
        ip = ip or get_request_ip(request)
        vcode = request.META.get('HTTP_X_AUTH_VCODE')
        if not vcode:
            raise BizException(ERROR_VCODE_EMPTY)
        if not safe_dog_client.verify_token(user['id'], vcode, ip):
            raise BizException(ERROR_VCODE_INCORRECT)
